package rssfeed;

import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author Glaucio
 */
public class NewJFrame extends javax.swing.JFrame {

  /** Creates new form NewJFrame */
  public NewJFrame() {
    initComponents();
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    memo = new javax.swing.JTextArea();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    memo.setColumns(20);
    memo.setRows(5);
    jScrollPane1.setViewportView(memo);

    jButton1.setText("Atualizar");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton1ActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 511, Short.MAX_VALUE)
          .addComponent(jButton1))
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jButton1)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)
        .addContainerGap())
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    memo.setText("");
    writeNews();
  }//GEN-LAST:event_jButton1ActionPerformed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

      public void run() {
        new NewJFrame().setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton jButton1;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JTextArea memo;
  // End of variables declaration//GEN-END:variables

  private String limpaHtml(String s) {
    String a = s;

    a = a.replace("<strong>", "");
    a = a.replace("</strong>", "");
    a = a.replace("<p>&nbsp;</p>", "");
    a = a.replace("</p>", "");
    a = a.replace("&#8211;", "");
    a = a.replace("<br/>", "");
    //<a  href = "http://blogs.estadao.com.br/transito/files/2012/04/transito_SP2_6203.jpg" >
    //a = a.replaceAll("<[iI][mM][gG][a-zA-Z0-9s=\".]*((src)=s*(?:”([^\"]*)”|’[^']*’))[a-zA-Z0-9s=\".]*/*>(?:</[iI][mM][gG]>)*", "");
    //a = a.replaceAll("<a href=\" </a>$", "");
    //a = a.replace("<p>Mande e receba informações sobre o trânsito na cidade de São Paulo pelo <a href=\"http://twitter.com/#%21/estadao/\">twitter do Estadão</a>, usando a hashtag #transito_estadao e envie para @Estadão. Baixe o <a href=\"http://itunes.apple.com/br/app/id457072078?mt=8\">aplicativo do trânsito</a> no iTunes.</p>", "");

    return a;
  }

  public void writeNews() {
    try {
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      URL u = new URL("http://blogs.estadao.com.br/transito/feed/"); // your feed url
      Document doc = builder.parse(u.openStream());
      NodeList nodes = doc.getElementsByTagName("item");

      for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        memo.setText(memo.getText() + "Data: " + getElementValue(element, "pubDate") + "\n");
        String post = getElementValue(element, "content:encoded");

        String[] posts = post.split("<p>");
        boolean achou = false;
        for (int j = 0; j < posts.length; j++) {
          String p = limpaHtml(posts[j]);

          if ((p.length() > 0)) {
            int c = p.codePointAt(0);
            if ((c >= 48) && (c <= 57)) {
              achou = true;
              memo.setText(memo.getText() + p);
            }
          }
        }

        memo.setText(memo.getText() + "\n");
      }//for
    }//try
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  private String getCharacterDataFromElement(Element e) {
    try {
      Node child = e.getFirstChild();
      if (child instanceof CharacterData) {
        CharacterData cd = (CharacterData) child;
        return cd.getData();
      }
    } catch (Exception ex) {
    }
    return "";
  } //private String getCharacterDataFromElement

  protected float getFloat(String value) {
    if (value != null && !value.equals("")) {
      return Float.parseFloat(value);
    }
    return 0;
  }

  protected String getElementValue(Element parent, String label) {
    return getCharacterDataFromElement((Element) parent.getElementsByTagName(label).item(0));
  }
}
